#include "agents.h"
#include <wx/string.h>
#include <wx/tokenzr.h>

// SmartChatAgent 实现
wxString SmartChatAgent::ProcessMessage(const wxString& message) {
    wxString lowerMsg = message.Lower();
    
    // 处理问候语
    if (lowerMsg.Contains(wxT("hello")) || lowerMsg.Contains(wxT("hi")) || 
        lowerMsg.Contains(wxT("greeting")) || lowerMsg.Contains(wxT("你好"))) {
        return HandleGreeting(message);
    }
    
    // 处理代码生成请求
    if (lowerMsg.Contains(wxT("python")) || lowerMsg.Contains(wxT("代码")) || 
        lowerMsg.Contains(wxT("program")) || lowerMsg.Contains(wxT("写"))) {
        if (lowerMsg.Contains(wxT("fibonacci")) || lowerMsg.Contains(wxT("斐波那契"))) {
            return GeneratePythonCode(wxT("fibonacci"));
        }
        return GeneratePythonCode(message);
    }
    
    if (lowerMsg.Contains(wxT("c++")) || lowerMsg.Contains(wxT("cpp"))) {
        return GenerateCppCode(message);
    }
    
    if (lowerMsg.Contains(wxT("html")) || lowerMsg.Contains(wxT("网页"))) {
        return GenerateHTMLCode(message);
    }
    
    if (lowerMsg.Contains(wxT("javascript")) || lowerMsg.Contains(wxT("js"))) {
        return GenerateJavaScriptCode(message);
    }
    
    // 处理解释请求
    if (lowerMsg.Contains(wxT("解释")) || lowerMsg.Contains(wxT("什么是")) || 
        lowerMsg.Contains(wxT("explain")) || lowerMsg.Contains(wxT("what is"))) {
        return GenerateExplanation(message);
    }
    
    // 创意响应
    return GenerateCreativeResponse(message);
}

wxString SmartChatAgent::HandleGreeting(const wxString& message) {
    return wxT("👋 你好！我是智能对话助手，类似 DeepSeek。我可以帮你：\n\n")
           wxT("• 编写 Python、C++、HTML、JavaScript 代码\n")
           wxT("• 解释编程概念和技术问题\n")
           wxT("• 提供创意建议和解决方案\n")
           wxT("• 分析代码和项目结构\n\n")
           wxT("请告诉我你需要什么帮助！");
}

wxString SmartChatAgent::GeneratePythonCode(const wxString& requirement) {
    wxString lowerReq = requirement.Lower();
    
    if (lowerReq.Contains(wxT("fibonacci")) || lowerReq.Contains(wxT("斐波那契"))) {
        return wxT("🐍 Python 斐波那契数列实现：\n\n")
               wxT("```python\ndef fibonacci(n):\n")
               wxT("    if n <= 0:\n        return []\n    elif n == 1:\n        return [0]\n    elif n == 2:\n        return [0, 1]\n    \n    fib_sequence = [0, 1]\n    for i in range(2, n):\n        next_fib = fib_sequence[i-1] + fib_sequence[i-2]\n        fib_sequence.append(next_fib)\n    \n    return fib_sequence\n\n# 示例使用\nif __name__ == \"__main__\":\n    n = 10\n    result = fibonacci(n)\n    print(f\"前{n}个斐波那契数: {result}\")\n```\n\n")
               wxT("这个实现：\n• 处理边界情况（n <= 0, n=1, n=2）\n• 使用循环高效生成序列\n• 返回完整的斐波那契数列");
    }
    
    if (lowerReq.Contains(wxT("calculator")) || lowerReq.Contains(wxT("计算器"))) {
        return wxT("🐍 Python 简单计算器：\n\n")
               wxT("```python\nclass Calculator:\n    def add(self, a, b):\n        return a + b\n    \n    def subtract(self, a, b):\n        return a - b\n    \n    def multiply(self, a, b):\n        return a * b\n    \n    def divide(self, a, b):\n        if b == 0:\n            raise ValueError(\"除数不能为零\")\n        return a / b\n\n# 使用示例\ncalc = Calculator()\nprint(f\"5 + 3 = {calc.add(5, 3)}\")\nprint(f\"10 - 4 = {calc.subtract(10, 4)}\")\nprint(f\"6 * 7 = {calc.multiply(6, 7)}\")\nprint(f\"15 / 3 = {calc.divide(15, 3)}\")\n```");
    }
    
    return wxT("🐍 Python 代码示例：\n\n")
           wxT("```python\n# 简单的文件操作示例\nimport os\n\ndef read_file(filename):\n    \"\"\"读取文件内容\"\"\"\n    try:\n        with open(filename, 'r', encoding='utf-8') as file:\n            return file.read()\n    except FileNotFoundError:\n        return f\"文件 {filename} 不存在\"\n\ndef write_file(filename, content):\n    \"\"\"写入文件内容\"\"\"\n    with open(filename, 'w', encoding='utf-8') as file:\n        file.write(content)\n    return f\"内容已写入 {filename}\"\n\n# 使用示例\nif __name__ == \"__main__\":\n    content = \"Hello, Python!\\n这是一段测试文本。\"\n    write_file(\"test.txt\", content)\n    print(read_file(\"test.txt\"))\n```");
}

wxString SmartChatAgent::GenerateCppCode(const wxString& requirement) {
    return wxT("⚡ C++ 代码示例：\n\n")
           wxT("```cpp\n#include <iostream>\n#include <vector>\n#include <string>\n\n// 简单的学生类\nclass Student {\nprivate:\n    std::string name;\n    int age;\n    double grade;\n\npublic:\n    Student(const std::string& n, int a, double g) \n        : name(n), age(a), grade(g) {}\n    \n    void displayInfo() const {\n        std::cout << \"姓名: \" << name << std::endl;\n        std::cout << \"年龄: \" << age << std::endl;\n        std::cout << \"成绩: \" << grade << std::endl;\n    }\n    \n    bool isExcellent() const {\n        return grade >= 90.0;\n    }\n};\n\n// 主函数\nint main() {\n    Student student1(\"张三\", 20, 95.5);\n    Student student2(\"李四\", 19, 85.0);\n    \n    std::cout << \"=== 学生信息 ===\" << std::endl;\n    student1.displayInfo();\n    std::cout << \"优秀学生: \" << (student1.isExcellent() ? \"是\" : \"否\") << std::endl;\n    \n    std::cout << \"\\n=== 学生信息 ===\" << std::endl;\n    student2.displayInfo();\n    std::cout << \"优秀学生: \" << (student2.isExcellent() ? \"是\" : \"否\") << std::endl;\n    \n    return 0;\n}\n```\n\n")
           wxT("这个C++示例展示了：\n• 类的定义和使用\n• 构造函数和成员函数\n• 访问控制（private/public）\n• 简单的业务逻辑");
}

wxString SmartChatAgent::GenerateHTMLCode(const wxString& requirement) {
    return wxT("🌐 HTML 登录页面示例：\n\n")
           wxT("```html\n<!DOCTYPE html>\n<html lang=\"zh-CN\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>用户登录</title>\n    <style>\n        body {\n            font-family: Arial, sans-serif;\n            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n            height: 100vh;\n            display: flex;\n            justify-content: center;\n            align-items: center;\n            margin: 0;\n        }\n        \n        .login-container {\n            background: white;\n            padding: 40px;\n            border-radius: 10px;\n            box-shadow: 0 15px 35px rgba(0,0,0,0.1);\n            width: 100%;\n            max-width: 400px;\n        }\n        \n        .login-title {\n            text-align: center;\n            margin-bottom: 30px;\n            color: #333;\n            font-size: 24px;\n            font-weight: bold;\n        }\n        \n        .form-group {\n            margin-bottom: 20px;\n        }\n        \n        .form-group label {\n            display: block;\n            margin-bottom: 5px;\n            color: #555;\n            font-weight: bold;\n        }\n        \n        .form-group input {\n            width: 100%;\n            padding: 12px;\n            border: 2px solid #ddd;\n            border-radius: 5px;\n            font-size: 16px;\n        }\n        \n        .login-btn {\n            width: 100%;\n            padding: 12px;\n            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n            color: white;\n            border: none;\n            border-radius: 5px;\n            font-size: 16px;\n            cursor: pointer;\n        }\n    </style>\n</head>\n<body>\n    <div class=\"login-container\">\n        <div class=\"login-title\">用户登录</div>\n        <form>\n            <div class=\"form-group\">\n                <label for=\"username\">用户名:</label>\n                <input type=\"text\" id=\"username\" required>\n            </div>\n            \n            <div class=\"form-group\">\n                <label for=\"password\">密码:</label>\n                <input type=\"password\" id=\"password\" required>\n            </div>\n            \n            <button type=\"submit\" class=\"login-btn\">登录</button>\n        </form>\n    </div>\n</body>\n</html>\n```");
}

wxString SmartChatAgent::GenerateJavaScriptCode(const wxString& requirement) {
    return wxT("🎯 JavaScript 示例：\n\n")
           wxT("```javascript\n// 现代 JavaScript 特性示例\nclass TodoApp {\n    constructor() {\n        this.todos = [];\n    }\n    \n    addTodo(text) {\n        const todo = {\n            id: Date.now(),\n            text: text,\n            completed: false,\n            createdAt: new Date()\n        };\n        this.todos.push(todo);\n    }\n    \n    toggleTodo(id) {\n        this.todos = this.todos.map(todo => \n            todo.id === id ? { ...todo, completed: !todo.completed } : todo\n        );\n    }\n    \n    deleteTodo(id) {\n        this.todos = this.todos.filter(todo => todo.id !== id);\n    }\n    \n    getStats() {\n        const total = this.todos.length;\n        const completed = this.todos.filter(todo => todo.completed).length;\n        return { total, completed, pending: total - completed };\n    }\n}\n\n// 使用示例\nconst app = new TodoApp();\napp.addTodo(\"学习 JavaScript\");\napp.addTodo(\"编写 AI 助手\");\napp.toggleTodo(app.todos[0].id);\n\nconst stats = app.getStats();\nconsole.log(`总计: ${stats.total}, 已完成: ${stats.completed}`);\n```");
}

wxString SmartChatAgent::GenerateExplanation(const wxString& topic) {
    wxString lowerTopic = topic.Lower();
    
    if (lowerTopic.Contains(wxT("oop")) || lowerTopic.Contains(wxT("面向对象"))) {
        return wxT("📚 面向对象编程 (OOP) 解释：\n\n")
               wxT("面向对象编程是一种编程范式，基于\"对象\"的概念。主要特点：\n\n")
               wxT("🔷 **四大支柱**：\n")
               wxT("• **封装**：将数据和操作数据的方法绑定在一起\n")
               wxT("• **继承**：子类可以继承父类的属性和方法\n")
               wxT("• **多态**：同一操作作用于不同对象可以有不同的行为\n")
               wxT("• **抽象**：提取关键特征，忽略不必要的细节\n\n")
               wxT("🔷 **核心概念**：\n")
               wxT("• **类**：对象的蓝图或模板\n")
               wxT("• **对象**：类的实例\n")
               wxT("• **方法**：对象的行为\n")
               wxT("• **属性**：对象的状态");
    }
    
    if (lowerTopic.Contains(wxT("machine learning")) || lowerTopic.Contains(wxT("机器学习"))) {
        return wxT("🤖 机器学习解释：\n\n")
               wxT("机器学习是人工智能的一个分支，让计算机通过数据学习并改进性能。\n\n")
               wxT("🎯 **主要类型**：\n")
               wxT("• **监督学习**：使用带标签的数据训练模型\n")
               wxT("• **无监督学习**：发现无标签数据中的模式\n")
               wxT("• **强化学习**：通过试错学习最优策略\n\n")
               wxT("🛠️ **常见算法**：\n")
               wxT("• 线性回归、逻辑回归\n• 决策树、随机森林\n• 支持向量机\n• 神经网络");
    }
    
    return wxT("📖 知识解释：\n\n")
           wxT("我很乐意为你解释这个概念！请提供更具体的问题。");
}

wxString SmartChatAgent::GenerateCreativeResponse(const wxString& message) {
    return wxT("💫 创意响应：\n\n")
           wxT("我注意到你说：\"") + message + wxT("\"\n\n")
           wxT("作为AI助手，我可以帮你：\n\n")
           wxT("🎯 **代码开发**\n")
           wxT("• 编写各种编程语言的代码\n• 调试和优化代码\n• 设计算法和数据结构\n\n")
           wxT("📚 **学习指导**\n")
           wxT("• 解释编程概念\n• 提供学习路径建议\n• 解答技术问题\n\n")
           wxT("请告诉我你具体需要什么帮助！");
}

// CodeGeneratorAgent 实现
wxString CodeGeneratorAgent::ProcessMessage(const wxString& message) {
    return wxT("🔧 代码生成器为你服务！\n\n")
           wxT("我可以生成多种编程语言的代码：\n\n")
           wxT("• **Python**：数据分析、Web开发、自动化脚本\n")
           wxT("• **C++**：系统编程、游戏开发、高性能应用\n")
           wxT("• **HTML/CSS/JavaScript**：网页开发和前端界面\n")
           wxT("• **Java**：企业级应用、Android开发\n")
           wxT("• **SQL**：数据库查询和操作\n\n")
           wxT("请告诉我你想要生成什么代码！");
}

// CodeAnalysisAgent 实现
wxString CodeAnalysisAgent::ProcessMessage(const wxString& message) {
    if (message.Contains(wxT(".cbp")) || message.Contains(wxT("项目"))) {
        return AnalyzeCBPFile(message);
    }
    
    return wxT("🔍 代码分析助手为你服务！\n\n")
           wxT("我可以分析：\n\n")
           wxT("• **CBP项目文件**：解析Code::Blocks项目结构\n")
           wxT("• **代码质量**：检查代码规范和最佳实践\n")
           wxT("• **依赖关系**：分析模块和库的依赖\n")
           wxT("• **性能建议**：提供优化建议\n\n")
           wxT("请提供CBP文件路径或代码进行分析！");
}

wxString CodeAnalysisAgent::AnalyzeCBPFile(const wxString& filepath) {
    return wxT("📊 CBP项目分析报告\n\n")
           wxT("**项目文件**: ") + filepath + wxT("\n\n")
           wxT("**分析结果**:\n")
           wxT("• 项目类型: C++ 应用程序\n")
           wxT("• 构建目标: Debug 和 Release\n")
           wxT("• 编译器: GCC\n")
           wxT("• 依赖库: wxWidgets\n\n")
           wxT("**建议**:\n")
           wxT("• 确保所有源文件路径正确\n")
           wxT("• 检查编译器设置\n")
           wxT("• 验证库依赖关系");
}
